package com.tamakloe.guestbook;

import java.util.Collection;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import static com.tamakloe.guestbook.GuestbookConstants.PAGE_SIZE;
import static com.tamakloe.guestbook.GuestbookConstants.GREETING_ORDER_ASC;
import static com.tamakloe.guestbook.GuestbookConstants.GREETING_ORDER_DESC;


public class GreetingJdoDao implements GreetingDao{

	@SuppressWarnings("unchecked")
	public Collection<Greeting> getAllGreetings(int page) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(Greeting.class);
		try{
			return pm.detachCopyAll((Collection<Greeting>)query.execute());
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	public Collection<Greeting> getGreetingsByCustomFilter(String order, int page) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(Greeting.class);
		if (order == GREETING_ORDER_DESC){
			query.setOrdering("date " + GREETING_ORDER_DESC);
		}else {
			query.setOrdering("date " + GREETING_ORDER_ASC);
		}
		query.setRange(PAGE_SIZE * (page - 1), PAGE_SIZE * page);
		try{
			return pm.detachCopyAll((Collection<Greeting>) query.execute());
		} finally {
			pm.close();
		}
	}

	public void postGreeting(Greeting greeting) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try{
			pm.makePersistent(greeting);
		} finally {
			pm.close();
		}
		
	}

}
